<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">

        <a-collapse-panel key="1" header="往来单位信息">
        <a-row :gutter="48">
          <a-col :span="8">
            <a-form-model-item label="企业名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="enterpriseName">
              <a-input :disabled="formDisabled" v-model="model.enterpriseName" placeholder="请输入企业名称"  @change="changeEnterpriseName"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="商户类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="commercialType">
              <j-dict-select-tag :disabled="formDisabled" type="list" v-model="model.commercialType" dictCode="commercial_type" placeholder="请选择商户类型" @blur="commercialTypeBlur" disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="企业信用代码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="enterpriseCreditCode">
              <a-input :disabled="formDisabled" v-model="model.enterpriseCreditCode" placeholder="请输入企业信用代码" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="企业类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="enterpriseType">
              <j-dict-select-tag :disabled="formDisabled" type="list" v-model="model.enterpriseType" dictCode="enterprise_type" placeholder="请选择企业类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="法定代表人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="legalRepresentative">
              <a-input :disabled="formDisabled" v-model="model.legalRepresentative" placeholder="请输入法定代表人"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="企业地址" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="enterpriseAddress">
              <a-input :disabled="formDisabled" :max-length="100" v-model="model.enterpriseAddress" placeholder="请输入企业地址"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="公司注册时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="registerDate">
              <a-date-picker :disabled="formDisabled"
                  :disabled-date="disabledDate"
                  placeholder="请选择公司注册时间" v-model="model.registerDate"  style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="注册资本" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="registerCapital">
              <a-input :disabled="formDisabled" v-model="model.registerCapital" placeholder="请输入注册资本" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="8">
            <a-form-model-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="liaison">
              <a-input :disabled="formDisabled" v-model="model.liaison" placeholder="请输入联系人"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="联系电话" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="liaisonMobile">
              <a-input :disabled="formDisabled"    v-model="model.liaisonMobile" placeholder="请输入联系电话" style="width: 100%" />
            </a-form-model-item>
          </a-col> -->
          <a-col :span="8">
            <a-form-model-item label="收款账户名称" prop="bankAccountName">
              <a-input :disabled="formDisabled" v-model="model.bankAccountName" placeholder="请输入收款账户名称" />
            </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="开户行联行号"  prop="cnapsCode">
                <SelectFinanceKingdeeBankInput :disabled="formDisabled"  v-model="model.cnapsCode"  placeholder="请选择联行号"  @back="backCnapsCode" />
              </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="开户行" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bankName">
              <a-input :disabled="formDisabled" v-model="model.bankName" placeholder="请输入收款开户行"  disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="银行账号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bankAccountNo">
              <a-input :disabled="formDisabled" v-model="model.bankAccountNo" :max-length="32" placeholder="请输入银行账号"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="公司网址" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="companyWeb">
              <a-input :disabled="formDisabled" :max-length="100" v-model="model.companyWeb" placeholder="请输入公司网址"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-if="model.commercialType == 2">
            <a-form-model-item label="物料大类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="provisionBroad">
              <a-select
                v-model="model.provisionBroad"
                :disabled="formDisabled"
                placeholder="请选择物料大类"
                :getPopupContainer="(triggerNode)=>{ return triggerNode.parentNode}"
                :showSearch="true"
                :allowClear="true"
                :filterOption="filterOption"
                @change="handleChange"
              >
                <a-select-option v-for="item in provisionBroadList" :key="item.id" :value="item.id">{{item.categoryName}}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-if="model.commercialType == 2">
            <a-form-model-item label="物料小类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="provisionSmall">
              <a-select
                v-model="model.provisionSmall"
                :disabled="formDisabled"
                mode="multiple"
                :getPopupContainer="(triggerNode)=>{ return triggerNode.parentNode}"
                placeholder="请选择物料小类"
                :showArrow="true"
                :showSearch="true"
                :allowClear="true"
                :filterOption="filterOption"
                @change="provisionSmallChange"
              >
                <a-select-option v-for="item in provisionSmallList" :key="item.id" :value="item.id">{{item.categoryName}}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="主营业务" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="mainBussiness">
              <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.mainBussiness" rows="4" placeholder="请输入主营业务" />
            </a-form-model-item>
          </a-col>
        </a-row>
        </a-collapse-panel>
        <a-collapse-panel key="2" header="联系人信息">
          <erp-omc-customer-manager-contact-list ref="contactList" :disabled="formDisabled"></erp-omc-customer-manager-contact-list>
        </a-collapse-panel>
        <a-collapse-panel key="3" header="企业资质材料">
          <a-row :gutter="48">
          <a-col :span="6">
            <a-form-model-item label="法人身份证" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="legalRepresentativeCard">
              <j-image-upload :disabled="formDisabled" isMultiple v-model="model.legalRepresentativeCard"></j-image-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="营业执照" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bussinessLicense">
              <j-image-upload :disabled="formDisabled" isMultiple v-model="model.bussinessLicense"></j-image-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="供应商资质证书" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplierCertification">
              <j-image-upload :disabled="formDisabled" isMultiple v-model="model.supplierCertification"></j-image-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="以往合作合同" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="cooperativeContract">
              <j-image-upload :disabled="formDisabled" isMultiple v-model="model.cooperativeContract"></j-image-upload>
            </a-form-model-item>
          </a-col>
        </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import ErpOmcCustomerManagerContactList from './reference/ErpOmcCustomerManagerContactList';
  import SelectFinanceKingdeeBankInput from '@/views/scy/components/SelectFinanceKingdeeBankInput'
  import moment from 'moment'

  export default {
    name: 'ErpOmcCustomerManagerForm',
    components: {
      ErpOmcCustomerManagerContactList,
      SelectFinanceKingdeeBankInput
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      var validatorEnterpriseName = async (rule,value,callback)=>{
        if (value) {
          const that = this;
          var id = 1;
          if (this.model.id) {
            id = this.model.id
          }
          await getAction(this.url.queryByEnterpriseName, { enterpriseName: value, commercialType: this.model.commercialType, id: id }).then(res => {
            if (res.success) {
              if(res.result == '0') {
                that.onlyEnterpriseName = false
              } else if(res.result == '1' && that.enterpriseName == value) {
                that.onlyEnterpriseName = false
              } else {
                that.onlyEnterpriseName = true
              }
            } else {
              that.$message.warning(res.message)
            }
          })
          if(that.onlyEnterpriseName) {
            callback('企业名称已存在，请重新输入！')
            return;
          }
          callback()
        }
        callback()
      };
      return {
        model:{
          commercialType: 1
        },
        labelCol: {
        },
        activeKey: ['1', '2', '3'],
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 },
        },
        confirmLoading: false,
        validatorRules: {
        enterpriseName: [
            { required: true, message: '请输入企业名称!', trigger: 'blur'},
            { validator: validatorEnterpriseName, trigger: "blur" },
        ],
        commercialType: [
            { required: true, message: '请选择商户类型!', trigger: 'blur'},
        ],
        enterpriseType: [
            { required: true, message: '请选择企业类型!'},
        ],
        enterpriseCreditCode: [
          { validator: this.validatorEnterpriseCreditCode, trigger: "blur" }
        ],
          //迭代11去除
        // enterpriseType: [
        //     { required: true, message: '请选择企业类型!', trigger: 'blur'},
        // ],
        // legalRepresentative: [
        //     { required: true, message: '请输入法定代表人!', trigger: 'blur'},
        // ],
        enterpriseAddress: [
            { required: true, message: '请输入企业地址!', trigger: 'blur'},
        ],
          //迭代11去除
        // registerDate: [
        //     { required: true, message: '请选择公司注册时间!', trigger: 'change'},
        // ],
        // registerCapital: [
        //     { required: true, message: '请输入注册资本!', trigger: 'blur'},
        // ],
        // liaison: [
        //     { required: true, message: '请输入联系人!', trigger: 'blur'},
        // ],
        // liaisonMobile: [
        //     { required: true, message: '请输入联系电话!', trigger: 'blur'},
        //     { pattern: /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/, message: '请输入正确的手机号!' },
        // ],
        // provisionBroad: [
        //     { required: true, message: '请输入物料大类!', trigger: 'blur'},
        // ],
        // provisionSmall: [
        //     { required: true, message: '请输入物料小类!', trigger: 'blur'},
        // ],
        bankName: [],
        bankAccountNo: [],
        companyWeb: [
          { pattern: /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/, message: '请输入正确的网址!' },
        ],
        },
        url: {
          add: "/api/erp/purchase/supplier/erpPurchaseSupplier/add",
          edit: "/api/erp/purchase/supplier/erpPurchaseSupplier/edit",
          queryById: "/api/erp/purchase/supplier/erpPurchaseSupplier/queryById",
          queryProvisionBroadList: "/api/erp/purchase/material/erpMaterialCategory/queryAllParent",
          queryProvisionSmallList: "/api/erp/purchase/material/erpMaterialCategory/queryChildrenByParentId",
          queryByEnterpriseCreditCode: "/api/erp/purchase/supplier/erpPurchaseSupplier/queryByEnterpriseCreditCode",
          queryByEnterpriseName: "/api/erp/purchase/supplier/erpPurchaseSupplier/queryByEnterpriseName"
        },
        provisionBroadList: [],
        provisionSmallList: [],
        provisionSmall: null,
        enterpriseCreditCode: null,
        onlyEnterpriseCreditCode: true,
        enterpriseName: null,
        onlyEnterpriseName: true
      }
    },
    computed: {
      formDisabled() {
        return this.disabled
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      moment,
      // 去除空格
      changeEnterpriseName (e) {
        this.model.enterpriseName = e.target.value.replace(/\s/g, '');
        // 判断是否输入了特殊字符
        const regex = /^[\u4e00-\u9fa5\(\)（）\da-zA-Z&]{1,50}$/gi
        if (!regex.test(this.model.enterpriseName)) {
          // 如果输入的字符不满足要求，将其重置为上一次的值
          this.model.enterpriseName = this.model.enterpriseName.slice(0, -1);
        }
      },
      backCnapsCode(data) {
        if (data) {
          this.$set(this.model, 'bankName', data[0].bankBranchName)
        }
      },
      async validatorEnterpriseCreditCode(rule, value, callback) {
        if (value) {
          const that = this;
          await getAction('/api/erp/purchase/supplier/erpPurchaseSupplier/queryByEnterpriseCreditCode', { enterpriseCreditCode: value, commercialType: this.model.commercialType }).then(res => {
            if (res.success) {
              if (res.result == '0') {
                that.onlyEnterpriseCreditCode = false
              } else if (res.result == '1' && that.enterpriseCreditCode == value) {
                that.onlyEnterpriseCreditCode = false
              } else {
                that.onlyEnterpriseCreditCode = true
              }
            } else {
              that.$message.warning(res.message)
            }
          })
          if (that.onlyEnterpriseCreditCode) {
            callback('企业信用代码已存在，请重新输入！')
            return;
          }
          callback()
        }
        callback()
      },
      commercialTypeBlur(data) {
        this.$refs["form"].clearValidate('enterpriseCreditCode');
        this.$refs["form"].clearValidate('bankName');
        this.$refs["form"].clearValidate('bankAccountNo');
        if(data == 1) {
            this.validatorRules.enterpriseCreditCode = [
              { validator: this.validatorEnterpriseCreditCode, trigger: "blur" }
            ]
            this.validatorRules.bankName = []
          //迭代16.5 银行账户字段都放开，不需要限制
            // this.validatorRules.bankAccountNo = [
            //   { pattern: /^\d{10,25}$/, message: '请输入正确的银行账号!', trigger: 'blur' }
            // ]
        } else {
          this.validatorRules.enterpriseCreditCode = [
            { required: true, message: '请输入企业信用代码!', trigger: 'blur'},
            { validator: this.validatorEnterpriseCreditCode, trigger: "blur" },
          ]
          this.validatorRules.bankName = [
            { required: true, message: '请输入收款开户行!', trigger: 'blur' },
          ]
          this.validatorRules.bankAccountNo = [
            { required: true, message: '请输入银行账号!', trigger: 'blur' }
            //迭代16.5 银行账户字段都放开，不需要限制
            // { pattern: /^\d{10,25}$/, message: '请输入正确的银行账号!' },
          ]
        }
      },
      disabledDate(current) {
        return current > moment(new Date()).subtract('day')
      },
      provisionSmallChange(value) {
        this.provisionSmall = value.join(',');// 把数组项拼接成字符串，以逗号,分隔
      },
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      findProvisionBroadList() {
        const that = this
        that.provisionBroadList = []
        getAction(this.url.queryProvisionBroadList).then(res => {
          if (res.success) {
            res.result.forEach((res) => {
              that.provisionBroadList.push({ 'id':res.id, 'categoryName':res.categoryName })
            })
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      handleChange(value) {
        this.provisionSmallList = []
        this.$set(this.model, 'provisionSmall', undefined);
        this.$refs["form"].clearValidate('provisionSmall');
        if (!!value) {
          this.findProvisionSmallList(value)
        }
      },
      findProvisionSmallList(value) {
        const that = this
        const parentId = value
        getAction(this.url.queryProvisionSmallList, { parentId }).then(res => {
          if (res.success) {
            res.result.forEach((res) => {
              that.provisionSmallList.push({ 'id':res.id, 'categoryName':res.categoryName })
            })
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
        this.$refs["form"].clearValidate();
        this.model = Object.assign({}, record);
        // if (!!this.model.provisionSmall) {
        //   this.model.provisionSmall = this.model.provisionSmall.split(','); // 以逗号,为拆分的字符串
        // }
        // this.findProvisionBroadList()
        // this.provisionSmallList = []
        // if (!!this.model.provisionBroad) {
        //   this.findProvisionSmallList(this.model.provisionBroad)
        // }
        if (!!this.model.enterpriseCreditCode) {
          this.enterpriseCreditCode = this.model.enterpriseCreditCode
        } else {
          this.enterpriseCreditCode = null
        }
        if (!!this.model.enterpriseName) {
          this.enterpriseName = this.model.enterpriseName
        } else {
          this.enterpriseName = null
        }
        if (this.model.id) {
          this.$refs.contactList.loadData(1, this.model.id)
        } else {
          this.$refs.contactList.dataSource = []
        }
        this.commercialTypeBlur(1)
        this.visible = true;
      },
      submitForm () {
        let details = this.$refs.contactList.submitForm()
        if (!details.length > 0) {
          this.$message.warning('请添加联系人信息！');
          this.$emit('unButtonDisable');
          return
        }
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            // this.model.provisionSmall = this.provisionSmall
            this.model.detailList = details
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
                that.$emit('unButtonDisable');
              }
            }).catch((error) => {
              that.$emit('unButtonDisable');
            }).finally(() => {
              that.confirmLoading = false;
            })
          } else {
            that.$emit('unButtonDisable');
          }
        })
      },
    }
  }
</script>
